import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { config } from '../config';


export function authenticateJWT(req: Request, res: Response, next: NextFunction): void {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    res.status(401).json({ error: 'Missing authorization header' });
    return;
  }

  const token = authHeader.split(' ')[1];

  try {
    const decoded = jwt.verify(token, config.jwtSecret);
    (req as any).user = decoded; // 如果可能，尽量避免使用any，可以考虑为req.user定义一个接口
    next();
  } catch (err) {
    res.status(401).json({ error: 'Invalid or expired token' });
    return;
  }
}

// export function authenticateJWT(req: Request, res: Response, next: NextFunction){
//   const authHeader = req.headers.authorization;
//   if (!authHeader?.startsWith('Bearer ')) {
//     return res.status(401).json({ error: '缺少认证令牌' });
//   }
//
//   const token = authHeader.split(' ')[1];
//
//   try {
//     const decoded = jwt.verify(token, config.jwtSecret);
//     (req as any).user = decoded;
//     next();
//   } catch (err) {
//     return res.status(401).json({ error: '无效或过期的令牌' });
//   }
// }
